<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import { InputOtp, InputPassword } from '~/components/input';
import { flzxsqc } from '~/utils';

export const disable2FAPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./Disable2FA.vue')),
  {
    title: toRef(() => $t('6ho1Lh_0YlDkPxj0LLwo')),
    wrapClassName: 'ant-cover__Modal-drawer __screen-drawer',
    width: 400,
    rejectOnClose: true,
    maskClosable: false,
    centered: true,
    footer: null,
  },
);
</script>

<script setup lang="ts">
const emits = defineEmits<{
  close: [];
}>();

const { userInfoQry } = useUserStore();
const form = useAntdForm({
  enable_authenticator: {
    value: 0,
  },
  security_code: {
    value: '',
    rules: [
      { required: true, type: 'string', len: 6, message: $t('9QtWqL7hc0fzViFGn0Es') },
    ],
  },
  password: {
    value: '',
    rules: [{ required: true, type: 'string', message: $t('mfFbQx6d5lMlEhlQg5eV') }],
  },
}, {
  transform(state) {
    return { ...state, password: flzxsqc(state.password) };
  },
});
const switch2faMut = useMutation({
  mutationKey: [apis.apiAuthenticatorSwitch.id],
  mutationFn: apis.apiAuthenticatorSwitch.setDefaultConfig({
    successMessage: $t('lthFb6Fg2R3r2cFaJork'),
  }),
  onSuccess() {
    userInfoQry.refetch();
    emits('close');
  },
});
const disabled = computed(() => switch2faMut.isPending.value);

async function confirm() {
  switch2faMut.mutate({ requestBody: form.stateTF });
}
</script>

<template>
  <div
    class="h-90 rounded-t-4 bg-sys-layer-d"
    bodyClass="text-base text-sm text-sys-text-body max-h-75vh overflow-y-auto"
    @close="emits('close');"
  >
    <AForm v-bind="form.props" class="ant-cover__Form-compact" hideRequiredMark :disabled="disabled" layout="vertical" @finish="confirm()">
      <AFormItem v-bind="form.itemProps.password" :label="$t('ph7eJFfBmsn7xFyvj8')">
        <InputPassword v-model:value="form.state.password" :placeholder="$t('sbNd6Np6qPuRup0ZhZbYz')" />
      </AFormItem>
      <AFormItem v-bind="form.itemProps.security_code" :label="$t('vrOaTrsSDoDwKhZqxWG')">
        <InputOtp v-model:value="form.state.security_code" />
      </AFormItem>
      <AButton
        class="ant-cover__Button-3d-primary mt-4" type="primary" htmlType="submit" block
        :disabled="disabled" :loading="disabled"
      >
        {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
      </AButton>
    </AForm>
  </div>
</template>
